package com.carrental.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.rental.dto.VehicleInspectionDTO;
import com.carrental.rental.entity.VehicleInspection;
import com.carrental.rental.mapper.VehicleInspectionMapper;
import com.carrental.rental.service.VehicleInspectionService;
import com.carrental.rental.vo.VehicleInspectionVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆检查记录服务实现类
 */
@Service
public class VehicleInspectionServiceImpl extends ServiceImpl<VehicleInspectionMapper, VehicleInspection> implements VehicleInspectionService {

    /**
     * 创建车辆检查记录
     *
     * @param inspectionDTO 车辆检查记录DTO
     * @return 检查记录ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createInspection(VehicleInspectionDTO inspectionDTO) {
        VehicleInspection inspection = new VehicleInspection();
        BeanUtils.copyProperties(inspectionDTO, inspection);
        
        // 默认设置为未确认状态
        inspection.setUserConfirmed(0);
        inspection.setCreateTime(LocalDateTime.now());
        inspection.setUpdateTime(LocalDateTime.now());
        
        // 保存检查记录
        save(inspection);
        
        return inspection.getId();
    }

    /**
     * 根据ID获取车辆检查记录详情
     *
     * @param id 检查记录ID
     * @return 车辆检查记录VO
     */
    @Override
    public VehicleInspectionVO getInspectionById(Long id) {
        VehicleInspection inspection = getById(id);
        if (inspection == null) {
            return null;
        }
        
        return convertToVO(inspection);
    }

    /**
     * 根据订单ID获取车辆检查记录列表
     *
     * @param orderId 订单ID
     * @return 车辆检查记录VO列表
     */
    @Override
    public List<VehicleInspectionVO> getInspectionsByOrderId(Long orderId) {
        LambdaQueryWrapper<VehicleInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VehicleInspection::getOrderId, orderId);
        wrapper.orderByDesc(VehicleInspection::getCreateTime);
        
        List<VehicleInspection> list = list(wrapper);
        
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    /**
     * 根据订单ID和检查类型获取车辆检查记录
     *
     * @param orderId        订单ID
     * @param inspectionType 检查类型（1-取车检查，2-还车检查）
     * @return 车辆检查记录VO
     */
    @Override
    public VehicleInspectionVO getInspectionByOrderIdAndType(Long orderId, Integer inspectionType) {
        LambdaQueryWrapper<VehicleInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VehicleInspection::getOrderId, orderId);
        wrapper.eq(VehicleInspection::getInspectionType, inspectionType);
        
        VehicleInspection inspection = getOne(wrapper);
        if (inspection == null) {
            return null;
        }
        
        return convertToVO(inspection);
    }

    /**
     * 分页查询车辆检查记录
     *
     * @param page           分页参数
     * @param orderNo        订单号
     * @param vehicleId      车辆ID
     * @param inspectionType 检查类型
     * @param startTime      开始时间
     * @param endTime        结束时间
     * @return 分页车辆检查记录VO
     */
    @Override
    public Page<VehicleInspectionVO> pageInspections(Page<VehicleInspection> page, String orderNo, Long vehicleId, Integer inspectionType, String startTime, String endTime) {
        LambdaQueryWrapper<VehicleInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(orderNo), VehicleInspection::getOrderNo, orderNo);
        wrapper.eq(vehicleId != null, VehicleInspection::getVehicleId, vehicleId);
        wrapper.eq(inspectionType != null, VehicleInspection::getInspectionType, inspectionType);
        
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            wrapper.between(VehicleInspection::getCreateTime, start, end);
        }
        
        wrapper.orderByDesc(VehicleInspection::getCreateTime);
        
        Page<VehicleInspection> inspectionPage = page(page, wrapper);
        
        return convertToVOPage(inspectionPage);
    }

    /**
     * 用户确认检查记录
     *
     * @param id           检查记录ID
     * @param userSignature 用户签名图片URL
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userConfirmInspection(Long id, String userSignature) {
        VehicleInspection inspection = getById(id);
        if (inspection == null) {
            return false;
        }
        
        // 更新为已确认状态并添加用户签名
        inspection.setUserConfirmed(1);
        inspection.setUserSignature(userSignature);
        inspection.setUpdateTime(LocalDateTime.now());
        
        return updateById(inspection);
    }

    /**
     * 更新车辆检查记录
     *
     * @param inspectionDTO 车辆检查记录DTO
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInspection(VehicleInspectionDTO inspectionDTO) {
        if (inspectionDTO.getId() == null) {
            return false;
        }
        
        VehicleInspection inspection = getById(inspectionDTO.getId());
        if (inspection == null) {
            return false;
        }
        
        BeanUtils.copyProperties(inspectionDTO, inspection);
        inspection.setUpdateTime(LocalDateTime.now());
        
        return updateById(inspection);
    }

    /**
     * 转换检查记录实体为VO
     */
    private VehicleInspectionVO convertToVO(VehicleInspection inspection) {
        if (inspection == null) {
            return null;
        }
        
        VehicleInspectionVO vo = new VehicleInspectionVO();
        BeanUtils.copyProperties(inspection, vo);
        
        // 设置检查类型名称
        vo.setInspectionTypeName(getInspectionTypeName(inspection.getInspectionType()));
        
        // 设置用户确认状态名称
        vo.setUserConfirmedName(getUserConfirmedName(inspection.getUserConfirmed()));
        
        // TODO: 调用车辆服务获取车辆信息
        
        return vo;
    }

    /**
     * 转换检查记录分页为VO分页
     */
    private Page<VehicleInspectionVO> convertToVOPage(Page<VehicleInspection> page) {
        Page<VehicleInspectionVO> voPage = new Page<>();
        voPage.setCurrent(page.getCurrent());
        voPage.setSize(page.getSize());
        voPage.setTotal(page.getTotal());
        
        List<VehicleInspectionVO> voList = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 获取检查类型名称
     */
    private String getInspectionTypeName(Integer inspectionType) {
        if (inspectionType == null) {
            return "";
        }
        
        switch (inspectionType) {
            case 1:
                return "取车检查";
            case 2:
                return "还车检查";
            default:
                return "未知类型";
        }
    }

    /**
     * 获取用户确认状态名称
     */
    private String getUserConfirmedName(Integer userConfirmed) {
        if (userConfirmed == null) {
            return "";
        }
        
        switch (userConfirmed) {
            case 0:
                return "未确认";
            case 1:
                return "已确认";
            default:
                return "未知状态";
        }
    }
} 